package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.pojo.Item;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.SearchService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ItemClient itemClient;

    /**
     * 查询所有商品
     *
     * @param params 参数
     * @return
     */
    @Override
    public PageDTO<ItemDoc> search(RequestParams params) {
        try {
            //创建请求对象
            SearchRequest request = new SearchRequest("item");
//            String key = params.getKey();
//
//            //判断key是否为空
//            if (key == null || "".equals(key)) {
//                request.source().query(QueryBuilders.matchAllQuery());
//            } else {
//                request.source().query(QueryBuilders.matchQuery("all", key));
//            }
            buildBasicQuery(params, request);
            //分页
            int page = params.getPage();
            int size = params.getSize();
            request.source().from((page - 1) * size).size(size);

            //发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析响应
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 添加布尔查询
     *
     * @param params  请求参数
     * @param request 请求参数
     */
    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        // 1.构建BooleanQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        SearchSourceBuilder source = request.source();
        // 2.关键字搜索
        String key = params.getKey();
        if (key == null || "".equals(key)) {
            //创建高亮显示对象
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            //起始
            highlightBuilder.preTags("<em>").postTags("</em>").field("name").requireFieldMatch(false);
            source.highlighter(highlightBuilder);
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }
        // 3.品牌条件
        if (params.getBrand() != null && !params.getBrand().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        // 4.种类条件
        if (params.getCategory() != null && !params.getCategory().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("category", params.getCategory()));
        }

        //添加怕排序功能
        String sortBy = params.getSortBy();
        if (sortBy.equals("sold")) {
            source.sort(SortBuilders.fieldSort("sold").order(SortOrder.DESC));
        } else if (sortBy.equals("price")) {
            source.sort(SortBuilders.fieldSort("price").order(SortOrder.ASC));
        }
        // 6.价格
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders
                    .rangeQuery("price")
                    .gte(params.getMinPrice())
                    .lte(params.getMaxPrice())
            );
        }
        //添加算分函数
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                boolQuery,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                }
        );
        // 7.放入source
       source.query(functionScoreQueryBuilder);
    }

    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        try {
            //创建请求
            SearchRequest request = new SearchRequest("item");
            //添加查询条件
            buildBasicQuery(params, request);
            //聚合
            buildAggregation(request);
            //发出请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析结果
            Map<String, List<String>> map = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            //根据品牌名称获取结果
            List<String> brandList = getAggByName(aggregations, "brandAgg");
            List<String> categoryAgg = getAggByName(aggregations, "categoryAgg");

            map.put("brand", brandList);
            map.put("category", categoryAgg);
            //返回map
            return map;

        } catch (Exception e) {
            throw new RuntimeException();
        }
    }


    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 4.1.根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        // 4.2.获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        // 4.3.遍历
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            // 4.4.获取key
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }

    /**
     * 分桶聚合
     *
     * @param request
     */
    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(100)
        );
    }

    /**
     * 解析结果
     *
     * @param response 相应对象
     * @return 返回页面对象
     */
    private PageDTO<ItemDoc> handleResponse(SearchResponse response) {
        //解析相应
        SearchHits hits = response.getHits();
        //获取总条数
        long total = hits.getTotalHits().value;
        //得到文档数组
        SearchHit[] searchHits = hits.getHits();

        //创建一个新的集合
        List<ItemDoc> itemDocs = new ArrayList<>();
        //遍历
        for (SearchHit hit : searchHits) {
            //获取文档source
            String json = hit.getSourceAsString();
            //反序列化
            ItemDoc itemDoc = JSON.parseObject(json, ItemDoc.class);
            Map<String, HighlightField> map = hit.getHighlightFields();
            //判断该map集合是否为空
            if (!CollectionUtils.isEmpty(map)) {
                //根据字段获取高亮结果
                HighlightField highlightField = map.get("name");
                if (highlightField != null) {
                    //获取高亮值
                    String name = highlightField.getFragments()[0].toString();
                    //覆盖高亮结果
                    itemDoc.setName(name);
                }
            }
            //放入集合中
            itemDocs.add(itemDoc);
        }
        //封装返回
        return new PageDTO<>(total, itemDocs);

    }


    @Override
    public List<String> suggetions(String key) {
        try {
            //创建请求对象
            SearchRequest request = new SearchRequest("item");
            //创建source对象
            SearchSourceBuilder source = request.source();
            //添加查询条件
            source.suggest(new SuggestBuilder().addSuggestion("mySuggestion",
                    SuggestBuilders.completionSuggestion("suggestion")
                            .prefix(key)
                            .size(10)));
            //调用客户端发起请求,得到响应对象
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析请求
            Suggest suggest = response.getSuggest();
            //根据补全查询名称获取补全信息
            CompletionSuggestion suggestion = suggest.getSuggestion("mySuggestion");

            //获取options
            List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
            //创建一个新的集合
            List<String> list = new ArrayList<>();
            //遍历集合
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                //将内容添加到创建的集合中,返回集合
                list.add(text);
            }
            //返回集合
            return list;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }



    @Override
    public void deleteById(Long id) {
        try {
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("item", id.toString());
            // 2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    @Override
    public void insertById(Long id) {
        try {

            Item item = itemClient.findItemById(id);
            ItemDoc itemDoc = new ItemDoc(item);

            // 1.准备Request对象
            IndexRequest request = new IndexRequest("item").id(item.getId().toString());
            // 2.准备Json文档
            request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
            // 3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
